package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.EasyExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author kaixuan
 * @since 2020-05-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 获取上传的Excel文件使用EasyExcel读取
     * @param file
     * @param eduSubjectService  通过有参构造 可以让没有交给spring管理的类调用service
     */
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try{
            InputStream in = file.getInputStream();
            EasyExcel.read(in,SubjectData.class, new EasyExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取所有一级分类 二级分类
     * @return
     */
    @Override
    public List<OneSubject> nestedList(){
        //最终要的到的数据列表
        ArrayList<OneSubject> subjectNestedVoArrayList = new ArrayList<>();

        //查询所有的一级分类
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("parent_id",0);
        List<EduSubject> eduSubjectOne = baseMapper.selectList(queryWrapper1);

        //查询所有的二级分类
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.ne("parent_id",0);
        List<EduSubject> eduSubjectTwo = baseMapper.selectList(queryWrapper2);
        //填充一级分类
        for (EduSubject eduSubject : eduSubjectOne){
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject, oneSubject);
            subjectNestedVoArrayList.add(oneSubject);

            //填充二级分类
            //填充二级分类vo数据
            ArrayList<TwoSubject> subjectVoArrayList = new ArrayList<>();
            for(EduSubject e : eduSubjectTwo){
                if(eduSubject.getId().equals(e.getParentId())){
                    //创建二级类别vo对象
                    TwoSubject subjectVo = new TwoSubject();
                    BeanUtils.copyProperties(e, subjectVo);
                    subjectVoArrayList.add(subjectVo);
                }
            }
            oneSubject.setChildren(subjectVoArrayList);
        }
        return subjectNestedVoArrayList;
    }
}
